/**
*@项目名称: frt-api
*@文件名称: FileController.java
*@Date: 2018年11月20日
*@Copyright: 2018 www.abing.tech Inc. All rights reserved.
*/

package io.renren.modules.frt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import io.renren.common.utils.MapUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.modules.frt.entity.HistoryEntity;
import io.renren.modules.frt.entity.MonitorExcelEntity;
import io.renren.modules.frt.entity.MonitorHisEntity;
import io.renren.modules.frt.entity.TemplateEntity;
import io.renren.modules.frt.service.HistoryService;
import io.renren.modules.frt.service.MonitorExcelService;
import io.renren.modules.frt.service.MonitorHisService;
import io.renren.modules.frt.service.TemplateService;
import io.renren.modules.frt.utils.PoiUtils;

/**
 * 文件上传下载控制器
 * 
 * @author qibing.huang
 * @date 2018年11月20日
 */
@RestController
@RequestMapping("frt/file")
public class FileController {

	@Value("${frt.file.uploadPath}")
	private String path;
	@Autowired
	private TemplateService templateService;
	@Autowired
	private MonitorExcelService monitorExcelService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private MonitorHisService monitorHisService;

	/**
	 * 文件上传
	 * 
	 * @param file
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public R fileUpload(@RequestParam("file") MultipartFile file) {
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();

			String filepath = path + "/" + fileName;
			File dest = new File(filepath);

			if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
				dest.getParentFile().mkdir();
			}
			try {
				file.transferTo(dest); // 保存文件
				
				//解析模板
				try {
					monitorExcelService.deleteByMap(new MapUtils().put("1", "1"));
					List<MonitorExcelEntity> list = PoiUtils.parseMonitor(new FileInputStream(dest));
					monitorExcelService.insertBatch(list);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				return R.ok("上传成功！").put("name", fileName).put("url", filepath).put("fileId", UUID.randomUUID().toString());
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return R.error("上传失败！");
	}
	
	/**
	 * 文件上传
	 * 
	 * @param file
	 * @return Map<String,Object>
	 */
	@RequestMapping(value = "/hisUpload", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public R hisUpload(@RequestParam("file") MultipartFile file) {
		if (!file.isEmpty()) {
			String fileName = file.getOriginalFilename();

			String filepath = path + "/" + fileName;
			File dest = new File(filepath);

			if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
				dest.getParentFile().mkdir();
			}
			try {
				file.transferTo(dest); // 保存文件
				
				String fileId = UUID.randomUUID().toString();
				
				//解析表1的历史数据
				try {
					monitorHisService.deleteByMap(new MapUtils().put("1", "1"));
					List<MonitorHisEntity> list = PoiUtils.parseMonitorHis(new FileInputStream(dest), fileId);
					monitorHisService.insertBatch(list);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				return R.ok("上传成功！").put("name", fileName).put("url", filepath).put("fileId", fileId);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return R.error("上传失败！");
	}

	/**
	 * 文件下载
	 * 
	 * @param fileName
	 * @param flag
	 * @return ResponseEntity<?>
	 */
	@RequestMapping(value = "/fileDownload", method = RequestMethod.GET)
	public ResponseEntity<?> fileDownload(@RequestParam String fileId) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		
		TemplateEntity temp = templateService.selectOne(new EntityWrapper<TemplateEntity>().eq("file_id", fileId));
		Assert.isNull(temp, "文件id错误");
		String filepath = temp.getUrl();
		
		String fileName = filepath.substring(filepath.lastIndexOf("/") + 1);

		InputStream is = null;

		try {
			headers.add("Content-Disposition",
					String.format("attachment; filename=\"%s\"", new String(fileName.getBytes("GBK"), "ISO8859-1")));

			is = new FileInputStream(new File(filepath));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");

		return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE))
				.body(new InputStreamResource(is));
	}
	
	/**
	 * 文件下载
	 * 
	 * @param fileName
	 * @param flag
	 * @return ResponseEntity<?>
	 */
	@RequestMapping(value = "/hisDownload", method = RequestMethod.GET)
	public ResponseEntity<?> hisDownload(@RequestParam String fileId) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		
		HistoryEntity temp = historyService.selectOne(new EntityWrapper<HistoryEntity>().eq("file_id", fileId));
		Assert.isNull(temp, "文件id错误");
		String filepath = temp.getUrl();
		
		String fileName = filepath.substring(filepath.lastIndexOf("/") + 1);

		InputStream is = null;

		try {
			headers.add("Content-Disposition",
					String.format("attachment; filename=\"%s\"", new String(fileName.getBytes("GBK"), "ISO8859-1")));

			is = new FileInputStream(new File(filepath));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");

		return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType(MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE))
				.body(new InputStreamResource(is));
	}
}
